package com.sike.controller;

import com.sike.service.DrugService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
public class DrugImageController {

    private static final Logger logger = LoggerFactory.getLogger(DrugImageController.class);

    // 上传文件夹路径
    @Value("${file.upload-dir}")
    private String uploadDir;

    @Autowired
    private DrugService drugService;

    @PostConstruct
    public void init() {
        try {
            Files.createDirectories(Paths.get(uploadDir));
        } catch (IOException e) {
            logger.error("初始化时无法创建上传文件夹:", e);
            throw new RuntimeException("无法创建上传文件夹!");
        }
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("drugId") Integer drugId) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }

        try {
            // 构建文件保存的文件名
            String filename = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            // 构建完整的文件保存路径
            Path path = Paths.get(uploadDir + filename);
            // 使用 REPLACE_EXISTING 选项来覆盖已存在的文件
            Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
            // 保存文件路径到数据库
            drugService.updateDrugImage(drugId, filename);

            return "文件上传成功：" + filename;
        } catch (IOException e) {
            logger.error("上传文件时发生错误：", e);
            return "上传失败，错误：" + e.getMessage();
        }
    }

}
